<?php
$db = new Database();

$isGeneral = isGeneralSitePage($_SERVER['SCRIPT_NAME']);

$selectSQL = sprintf("SELECT m.*, mc.name AS CategoryName, mc.type FROM modules m 
			  INNER JOIN module_categories mc ON mc.id = m.module_category_id 
              INNER JOIN user_role_menus rm ON rm.menu_id = mc.id
			  WHERE type = '" . ($isGeneral ? 'general' : 'site_specific') . "' 
			  AND mc.active = 1 AND m.active = 1 AND rm.role_id = %s
			  ORDER BY mc.position ASC, m.id ", $db->sanitizeInput($_SESSION['User_Role'], 'int'));

$db->query($selectSQL, true);

if ($db->getResultCount() == 0) {
    echo '
			<div class="nav_group"> 
				<div class="header">Site Management</div>
				<div class="content">
				   <ul>
				   	<li><a href="sites.php">Sites Home</a></li>
				   </ul>
				</div>
			</div>
		';

    return;
}

$lastCat = "";
for ($i = 0; $i < $db->getResultCount(); $i++) {
    $row = $db->getRow($i);
    $catName = $row['CategoryName'];

    if ($catName != $lastCat) {
        if ($i > 0) {
            echo '
						</ul>
					</div>
				 </div>
				';
        }

        // cache the new group
        $lastCat = $catName;


        echo '<div class="nav_group"> 
                <div class="header">' . $row['CategoryName'] . '</div>
                <div class="content">
                   <ul>
			';
    }

    if ($catName == $lastCat) {
        $module = str_replace("_module", "", String::camelToLowerWithUnderscores($row['class']));
        echo '<li><a href="index.php?module=' . $module . '">&raquo; ' . $row['name'] . '</a></li>';
    }

    // end and close
    if ($i == $db->getResultCount() - 1) {
        echo '
					</ul>
				</div>
			 </div>
			';
        break;
    }
}
?>

<script type="text/javascript">
    pageManager.addLoadEvent(function() {

        if (!document.querySelectorAll) {
            return;
        }

        var group_headers = document.querySelectorAll(".nav_group .header");

        for (var i = 0; i < group_headers.length; i++) {
            var header = group_headers[i];
            header.contentId = i;
            header.onclick = function() {
                var content = this.parentNode.querySelector(".content");
                $p(content).toggleSlide();
            };
        }
    });
</script>